package ex2;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class Request implements Runnable {

	private Socket client;
	private String[] responses = new String[]{"901 OK","902 UNKNOWN","903 UNAUTHORISED","904 NOT FOUND","905 EOF"};
	private static final String password = "james";
	private boolean authorised = false;
	private String[][] files = new String[][]{
			{"file 1","This is the contents of file 1"},
			{"file 2","This is the contents of file 2"},
			{"file 3","This is the contents of file 3"},
	};
	
	
	public Request(Socket client){
		this.client = client;
	}
	
	public void run() {
		try{
			BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
		    DataOutputStream out = new DataOutputStream(client.getOutputStream());
			String request = null;
			while(request==null){
				Thread.sleep(50);
				request = in.readLine();
			}
			System.out.println();
			while(!request.substring(0,3).equals("103")){
				Thread.sleep(50);
				if(request.equals("SYSTEM EXIT")) Server.active = false;
				if(request.substring(0,10).equals("101 PASSWD")){
					if(request.substring(11).equals(password)){
						authorised = true;
						out.writeBytes(responses[0]);
					}
					else{
						out.writeBytes(responses[2]);
					}
				}
				else if(request.substring(0,10).equals("102 ACCESS")){
					if(!authorised){
						out.writeBytes(responses[2]);
					}
					else{
						String file = hasFile(request.substring(11));
						if(file!=null){
							out.writeBytes(responses[0]);
							//Would break this into individual lines but what's the point
							out.writeBytes(file);
							out.writeBytes(responses[4]);
						}
						else{
							out.writeBytes(responses[3]);
						}
					}
				}
				else{
					out.writeBytes(responses[1]);
				}
				request = in.readLine();
			}
			out.writeBytes(responses[0]);
			out.close();
			in.close();
			client.close();
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}

	public String hasFile(String filename){
		for(int i = 0; i < files.length; i++){
			if(files[i][0].equals(filename)) return files[i][1];
		}
		return null;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s = "101 PASSWD james";
		System.out.println(s.substring(11).equals(password));
	}

}
